package library.image;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Mr.Fan on 2016/2/2.
 */
public class BitmapTaskHandler {

    private static final Object lock = new Object();

    private static final ConcurrentHashMap<String, List<WeakReference<Object>>> queue = new ConcurrentHashMap<>();

    public static void addTask(final String tag, final Object task) {
        if (tag == null || task == null)
            return;
        synchronized (lock) {
            List<WeakReference<Object>> tasks;
            WeakReference<Object> wrht = new WeakReference<>(task);
            if (queue.containsKey(tag)) {
                tasks = queue.get(tag);
            } else {
                tasks = Collections.synchronizedList(new ArrayList<WeakReference<Object>>());
                queue.put(tag, tasks);
            }
            tasks.add(wrht);
        }
    }

    public static void remove(final String tag, final Object task) {
        if (tag == null || task == null)
            return;
        synchronized (lock) {
            if (queue.containsKey(tag)) {
                List<WeakReference<Object>> tasks = queue.get(tag);
                if (tasks != null && tasks.size() > 0) {
                    for (int i = 0; i < tasks.size(); i++) {
                        WeakReference<Object> reference = tasks.get(i);
                        Object check = reference.get();
                        if (check == null) {
                            tasks.remove(check);
                            continue;
                        } else if (task.equals(check)) {
                            tasks.remove(task);
                            return;
                        }
                    }
                }
            }
        }
    }

    public static void cancel(final String tag) {
        if (tag == null)
            return;
        synchronized (lock) {
            if (queue.containsKey(tag)) {
                List<WeakReference<Object>> tasks = queue.get(tag);
                if (tasks != null && tasks.size() > 0) {
                    for (WeakReference<Object> reference : tasks) {
                        Object task = reference.get();
                        if (task instanceof BitmapTask) {
                            ((BitmapTask) task).cancel();
                        } else if (task instanceof BitmapThread) {
                            ((BitmapThread) task).cancel();
                        }
                    }
                }
                tasks.clear();
                tasks = null;
                //移除对应的Key
                queue.remove(tag);
            }
        }
    }

}
